<template>
    <!-- 收货地址 -->
    <van-contact-card type="edit" :name="`${address.name} (${address.region_text})`" :tel="address.tel" v-if="address" @click="AddressSelect" />
    <van-contact-card type="add" v-else @click="AddressAdd" />

     <!-- 商品卡片 -->
    <van-card
        v-for="(item, key) in list"
        :title="item.product.name"
        :thumb="item.product.thumbs_text"
        :num="item.nums"
        @click-thumb="toProductInfo(item.proid)"
    >
        <template #title>
        <div class="title">{{item.product.name}}</div>
        </template>

        <!-- 卡片的插槽部分 -->
        <template #desc v-if="item.attrs">
        <van-tag v-for="(attr,index) in item.attrs" :key="index" class="tag" type="primary">{{attr.value}}</van-tag>
        </template>
        <template #desc v-else>
        <van-tag class="tag" type="danger">无规格数据</van-tag>
        </template>

        <template #tags>
        <div class="price">单价：￥{{item.price}}</div>
        </template>

        <template #price>
        <div class="price">合计：￥{{item.total}}</div>
        </template>
    </van-card>

    <van-cell title="支付方式" :value="PayActive.text" is-link @click="PayShow = true"/>
    
    <!-- 优惠券 -->
    <van-coupon-cell
        :coupons="CouponList"
        :chosen-coupon="CouponActive"
        @click = "CouponShow = true"
    />

    <van-popup
        v-model:show="CouponShow"
        round
        position="bottom"
        style="height: 90%;padding-top: 4px;"
    >
        <van-coupon-list
            :coupons="CouponList"
            :chosen-coupon="CouponActive"
            :exchange-button-disabled="true"
            :show-exchange-bar="false"
            @change="CouponChange"
        />
    </van-popup>

    <!-- 订单备注 -->
    <van-field
        v-model="remark"
        rows="2"
        autosize
        label="订单备注"
        type="textarea"
        maxlength="120"
        placeholder="请输入订单备注"
        show-word-limit
    />

    <!-- 提交动作栏 -->
    <van-submit-bar text-align="left" :price="total" button-text="确认支付" @submit="submit" />
    
    <!-- 支付方式选择器 -->
    <van-popup v-model:show="PayShow" position="bottom">
        <van-picker
        title="选择支付方式"
        :columns="PayList"
        @cancel="PayShow = false"
        @confirm="PayConfirm"
        />
    </van-popup>
</template>

<script setup>
    const {proxy} = getCurrentInstance()

    let cartids = proxy.$route.query.cartids ? proxy.$route.query.cartids : '0';

    //响应式数据
    let list = ref([])
    let address = ref(null)
    let remark = ref('')

    //支付方式
    let PayShow = ref(false)
    let PayActive = ref({text: '余额支付', value: 'money'})
    let PayList = ref([
        {text: '余额支付',value: 'money'},
        {text: '微信支付',value: 'wx'},
        {text: '支付宝',value: 'zfb'},
    ])

    //优惠券
    const CouponList = ref([]);
    const CouponActive = ref(-1);
    const CouponShow = ref(false);

    //生命周期
    onBeforeMount(()=>
    {
        CartInfo()
        AddressInfo()
        CouponInfo()
    })

     //合计的价格
    let total = computed(() => {
        var total = 0
        
        list.value.map((item) => total += parseFloat(item.total))

        if(CouponActive.value != -1)
        {
            var rate = CouponList.value[CouponActive.value].rate

            total = (total * rate).toFixed(2)
            
        }

        return parseFloat(total*100)
    })

    const CartInfo = async () => 
    {
        var params = {
            busid: proxy.$business.value.id,
            cartids
        }
        var result = await proxy.$POST({
            url: '/cart/index',
            params
        })

        if(result.code == 0)
        {
            proxy.$fail(result.msg)
            return false
        }

        result.data.map(item=>item.attrs = JSON.parse(item.attrs))

        list.value = result.data
    }

    //返回收货地址方法
    const AddressInfo = async () =>
    {
        //先判断cookie当中是否存在缓存
        var cached = proxy.$cookies.get('address') ? proxy.$cookies.get('address') : null

        if(cached)
        {
            address.value = cached
        }else
        {
            var result = await proxy.$POST({
                url: '/address/selected',
                params: {busid: proxy.$business.value.id}
            })

            if(result.code == 0)
            {
                proxy.$fail(result.msg)
                return false
            }
            
            address.value = result.data
        }

    }

    //返回优惠券方法
    const CouponInfo = async () => 
    {
        var result = await proxy.$POST({
            url: '/business/coupon',
            params: {busid: proxy.$business.value.id}
        })

        if(result.code && result.data.length > 0)
        {
            var coupons = []

            for(var item of result.data)
            {
                coupons.push({
                    id: item.id,
                    condition: item.coupon.status_text,
                    rate: item.coupon.rate,
                    name: item.coupon.title,
                    startAt: item.coupon.createtime,
                    endAt: item.coupon.endtime,
                    valueDesc: `${item.coupon.rate*100}`,
                    unitDesc: '折',
                })
            }

            CouponList.value = coupons
        }
    }

    //切换收货地址
    const AddressSelect = () => {
        proxy.$router.push({path: '/address/index',query: {action: 'select'}})
    }

    //添加收货地址
    const AddressAdd = () => proxy.$router.push('/address/add')

    //跳转到商品详情界面
    const toProductInfo = proid => proxy.$router.push({path: '/product/info', query: {proid}})

    //选择支付方式
    const PayConfirm = ({selectedOptions}) => 
    {
        PayShow.value = false
        PayActive.value = selectedOptions[0]
    }

    //选择优惠券
    const CouponChange = (index) => 
    {
        CouponShow.value = false
        CouponActive.value = index

        if(index != -1)
        {
            var total = 0
            list.value.map((item) => total += parseFloat(item.total))

            //计算
            var rate = CouponList.value[index].rate
            var price = total * rate
            var CouponPrice = total - price
            CouponPrice = parseFloat(CouponPrice*100).toFixed(2)
            CouponList.value[index].value = CouponPrice
        }
    }

    //提交订单
    const submit = async () =>
    {
        var params = {
            busid: proxy.$business.value.id,
            addrid: address.value.id,
            cartids: cartids,
            remark: remark.value,
            pay: PayActive.value.value
        }

        if(CouponActive.value != -1)
        {
            params.couponid = CouponList.value[CouponActive.value].id
        }

        var result = await proxy.$POST({
            url: '/order/add',
            params
        })
        
        if(result.code == 0)
        {
            proxy.$fail(result.msg);
            return false
        }

        proxy.$success({
            message: result.msg,
            onClose: () => 
            {
                proxy.$router.push('/business/index')
                return false
            } 
        })
    }
</script>